/**
 * 迁移来自 node_modules 包，有bug需要魔改
 */
import * as request from "request";
import * as crypto from "crypto";
import * as querystring from "querystring";

function baiduTranslate(
  appid = "",
  secret = "",
  to = "en",
  from = "auto",
  dict = 1,
  tts = 1
) {
  function signature(query: string) {
    let string = appid + query + "salt" + secret;
    const md5 = crypto.createHash("md5");
    md5.update(string);
    return md5.digest("hex");
  }

  function translate(q: string) {
    return new Promise((resolve, reject) => {
      var postData = {
        appid,
        salt: "salt",
        sign: signature(q),
        q,
        from: from,
        to: to,
        dict,
        tts,
      };
      request.post(
        {
          url: "http://api.fanyi.baidu.com/api/trans/vip/translate",
          form: querystring.stringify(postData),
        },
        function (err, httpResponse, body) {
          if (err) {
            console.error(err);
            reject(err);
          }
          try {
            body = JSON.parse(body);
            // resolve(body.trans_result[0].dst);
            resolve(body);
          } catch (e) {
            console.error("解析翻译请求出错", e);
            reject(e);
          }
        }
      );
    });
  }
  return translate;
}

export function translate(word: string): Promise<string> {
  return new Promise((resolve) => {
    try {
      baiduTranslate(
        "20220302001107214",
        "Yp9Ip4OXNOd6ELWgtzKD",
        "en",
        "zh"
      )(word)
        .then((data: any) => {
          if (data && data.trans_result) {
            resolve(data.trans_result[0].dst);
            return;
          }
          throw new Error(
            `\n百度翻译api调用异常 error_code: ${data.error_code}, error_msg: ${data.error_msg}`
          );
        })
        .catch((e) => {
          console.error("百度翻译时出错", e);
          resolve("");
        });
    } catch (e) {
      console.error("百度翻译时出错", e);
      resolve("");
    }
  });
}
